package com.system.es;

import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.client.http.JestHttpClient;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Classname EsConfig
 * @Description TODO
 * @Date 2023/2/28 11:30
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Configuration
public class EsConfig {

    @Value("${es.hostname}")
    private String hostName;

    @Value("${es.username}")
    private String userName;

    @Value("${es.password}")
    private String passWord;

    @Bean
    public RestHighLevelClient restHighLevelClient() {

        CredentialsProvider credentialsProvider =
                new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, passWord));

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(hostName, 9200, "http")
                ).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
        );
        return client;
    }

    @Bean
    public RestClient getRestClient(){
        RestClient restClient = RestClient.builder(
                new HttpHost(hostName, 9200, "http")).build();
        return restClient;
    }

    @Bean
    public JestHttpClient getEsClient() {
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig.Builder(
                "http://"+hostName+":9200")
                .multiThreaded(true)
                .readTimeout(5000)
                .build());

        return (JestHttpClient) factory.getObject();
    }
}
